<?php
namespace Home\Controller;

use Utuo\WechatActivityController;

class WechatVoteController extends WechatActivityController
{
    
    // activity config
    private $activity;
    
    // vote option
    private $options;

    public function init()
    {
        $this->activity = M('WechatActivityVote')->where(array(
            'cid' => $this->cid,
            'id' => $this->aid,
            'status' => 1,
            'is_deleted' => 0
        ))->find();
        $this->options = M('WechatActivityVoteOption')->where(array(
            'cid' => $this->cid,
            'aid' => $this->aid,
            'status' => 1,
            'is_deleted' => 0
        ))->select();
    }
    
    // 活动主页
    public function indexAction()
    {
        $this->init();
        
        $data = array(
            't.cid' => $this->cid,
            't.aid' => $this->aid,
            't.uid' => $this->userInfo['id'],
            't.date' => date('Ymd')
        );
        
        $ticket = M("WechatActivityVoteTicket t")->join("LEFT JOIN __WECHAT_ACTIVITY_VOTE_OPTION__ o ON t.oid=o.id ")
            ->field("t.*,o.name")
            ->where($data)
            ->find();
        
        // 视图
        $this->assign('userInfo', $this->userInfo);
        $this->assign('activity', $this->activity);
        $this->assign('options', $this->options);
        $this->assign('ticket', $ticket);
        $this->display();
    }
    
    // 活动规则
    public function ruleAction(){
        $this->init();
        $this->assign('activity',$this->activity);
        $this->display();
    }
    
    // 用户投票
    public function ajaxVoteAction()
    {
        $this->init();
        $m = M('WechatActivityVoteTicket');
        
        $date = date('Ymd');
        $uid = I('uid', 0, 'intval');
        $oid = I('oid', 0, 'intval');
        
        $data = array(
            'cid' => $this->cid,
            'aid' => $this->aid,
            'uid' => $uid,
            'date' => $date
        );
        
        // 检查投票时间
        $time = time();
        if ($time>$this->activity['endTime']){
            $this->ajaxError("投票已经结束~");
        } elseif ($time<$this->activity['startTime']){
            $this->ajaxError('投票尚未开始~');
        }
        
        // 检查今日是否已经投票
        $ticket = $m->where($data)->find();
        $ticket === false && $this->ajaxError('网络错误，请重试！');
        $ticket && $this->ajaxError('您今天已经投过票了~');
        
        $data['oid'] = $oid;
        $data['createTime'] = time();
        
        C("TOKEN_ON", false);
        
        if ($m->add($data)) {
            M("WechatActivityVoteOption")->where(array(
                'cid' => $this->cid,
                'aid' => $this->aid,
                'id' => $oid
            ))->setInc("voteCount");
            $this->ajaxSuccess('投票成功~');
        } else {
            $this->ajaxError('网络错误，请再试一次~' . $m->getError());
        }
    }
}